import React, { Component } from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { rootState } from "./store";
import { IAdmin, IAdminActionType } from "./store/reducers/admin";
import { IUser, IUserActionType } from "./store/reducers/user";

interface IProps {
  admin?: IAdmin;
  user?: IUser;
  changeAdminName?(): void;
  changeUserName?(): void;
}
class RCCExample extends Component<IProps> {
  changeUserName = () => {
    this.props.changeUserName && this.props.changeUserName();
  };
  changeAdminName = () => {
    this.props.changeAdminName && this.props.changeAdminName();
  };
  render() {
    console.log(this.props);

    return (
      <div>
        <h1>类组件使用redux</h1>
        {this.props.admin?.name}
        <br />
        {this.props.user?.name}
        <br />
        <button onClick={this.changeAdminName}>change admin name</button>
        <button onClick={this.changeUserName}>change user name</button>
      </div>
    );
  }
}
// 第一步把store 映射到props上
const mapStateToProps = (state: rootState) => {
  return { ...state.admin, ...state.user };
};
// 第二步修改store的值,方法映射到props上
const mapDispatchToProps = (dispatch: Dispatch) => ({
  changeAdminName: () => {
    dispatch({
      type: IAdminActionType.CHANGE,
      payload: {
        admin: {
          name: "change Admin YUSIR",
        },
      },
    });
  },
  changeUserName: () => {
    dispatch({
      type: IUserActionType.CHANGE,
      payload: {
        user: {
          name: "change user YUSIR",
        },
      },
    });
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(RCCExample);
